package tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author : Rookie
 * @description : 翻转二叉树
 * @date : 2023/10/10
 */
public class InvertBinaryTree {

    public static void main(String[] args) {
        int[] input = {1, 2, 3, -1, 5, -1, 4};
        TreeNode root = BinaryTreeUtil.buildTree(input);
        System.out.println("翻转之前：");
        BinaryTreeUtil.Traversal.sequenceTraversal(root);
        cycleImpl(root);
        System.out.println("\n翻转之后");
        BinaryTreeUtil.Traversal.sequenceTraversal(root);
    }

    private static void cycleImpl(TreeNode root) {
        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode curr = queue.poll();
            // 遍历到节点，交换节点的左右孩子
            swapChildren(curr);
            if (curr.left != null) {
                queue.offer(curr.left);
            }
            if (curr.right != null) {
                queue.offer(curr.right);
            }
        }
    }

    private static void recurseImpl(TreeNode root) {
        if (root == null) {
            return;
        }
        swapChildren(root);
        recurseImpl(root.left);
        recurseImpl(root.right);
    }

    private static void swapChildren(TreeNode root) {
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }
}
